<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px" class="search-form">
          <!-- <el-form-item label="终端key" prop="terminalKey">
            <el-input v-model="queryParams.terminalKey" placeholder="请输入终端key" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="mac地址" prop="terminalMac">
            <el-input v-model="queryParams.terminalMac" placeholder="请输入mac地址" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item> -->
          <el-form-item label="设备名称" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入设备名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <!-- <el-form-item label="设备系列" prop="series">
            <el-select v-model="queryParams.series" placeholder="请选择设备系列" clearable>
              <el-option v-for="dict in tel_device_series" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item> -->
          <!-- <el-form-item label="设备IP" prop="ip">
            <el-input v-model="queryParams.ip" placeholder="请输入设备IP" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item> -->
          <el-form-item label="设备编码" prop="deviceCode">
            <el-input v-model="queryParams.deviceCode" placeholder="请输入设备编码" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <!-- <el-form-item label="心跳频率" prop="heartbeatFrequency">
            <el-input
              v-model="queryParams.heartbeatFrequency"
              placeholder="请输入心跳频率"
              clearable
              style="width: 240px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="定时开机时间" prop="timeOn">
            <el-date-picker clearable v-model="queryParams.timeOn" type="date" value-format="YYYY-MM-DD" placeholder="请选择定时开机时间" />
          </el-form-item>
          <el-form-item label="定时关机时间" prop="timeOff">
            <el-date-picker clearable v-model="queryParams.timeOff" type="date" value-format="YYYY-MM-DD" placeholder="请选择定时关机时间" />
          </el-form-item> -->
          <el-form-item label="设备状态" prop="onlineStatus">
            <el-select v-model="queryParams.onlineStatus" placeholder="请选择状态" clearable>
              <el-option v-for="dict in online_status" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <!-- <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['device:telDevice:add']">新增</el-button>
          </el-col> -->
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['device:telDevice:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['device:telDevice:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['device:telDevice:export']">导出</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" icon="Refresh" @click="handleSync" v-hasPermi="['telDevice:telDevice:sync']">同步设备</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="User" @click="handleUpdateUser" :disabled="multiple" v-hasPermi="['telDevice:telDevice:updateUser']"
              >更新用户</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="Setting"
              @click="handleUpdateConfig"
              :disabled="multiple"
              v-hasPermi="['telDevice:telDevice:updateConfig']"
              >更新配置</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="SwitchButton"
              @click="handleRestart"
              :disabled="multiple"
              v-hasPermi="['telDevice:telDevice:restart']"
              >远程重启</el-button
            >
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table
        height="calc(100vh - 370px)"
        v-loading="loading"
        :data="telDeviceList"
        @selection-change="handleSelectionChange"
        @row-dblclick="(row)=>handleUpdate(row)"
      >
        <el-table-column type="selection" width="55" align="center" />
        <!-- <el-table-column label="ID" align="center" prop="id" v-if="true" /> -->
        <el-table-column label="设备名称" align="center" prop="name" />
        <!-- <el-table-column label="设备系列" align="center" prop="series">
          <template #default="scope">
            <dict-tag :options="tel_device_series" :value="scope.row.series" />
          </template>
        </el-table-column> -->
        <el-table-column label="单次通话时长(分)" align="center" prop="callTime">
          <template #default="scope">
            {{ scope.row.callTime || "不限制" }}
          </template>
        </el-table-column>
        <el-table-column label="设备IP" align="center" prop="ip" />
        <el-table-column label="设备编码" align="center" prop="deviceCode" />
        <!-- <el-table-column label="心跳频率" align="center" prop="heartbeatFrequency" /> -->
        <!-- <el-table-column label="最后在线时间" align="center" prop="offlineTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.offlineTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column> -->
        <el-table-column label="状态" align="center" prop="onlineStatus">
          <template #default="scope">
            <dict-tag :options="online_status" :value="scope.row.onlineStatus" />
          </template>
        </el-table-column>
        <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['device:telDevice:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['device:telDevice:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改视频话机管理对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="800px" append-to-body>
      <el-form ref="telDeviceFormRef" :model="form" :rules="rules" label-width="110px" :inline="true" class="add-form">
        <el-form-item label="设备名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入设备名称" />
        </el-form-item>
        <!-- <el-form-item label="设备系列" prop="series">
          <el-select v-model="form.series" placeholder="请选择设备系列">
            <el-option v-for="dict in tel_device_series" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="心跳频率" prop="heartbeatFrequency">
          <el-input v-model="form.heartbeatFrequency" placeholder="请输入心跳频率" />
        </el-form-item>
        <el-form-item label="设备IP" prop="ip">
          <el-input v-model="form.ip" placeholder="请输入设备IP" />
        </el-form-item>
        <el-form-item label="设备编码" prop="deviceCode">
          <el-input v-model="form.deviceCode" placeholder="请输入设备编码" />
        </el-form-item>
        <el-form-item label="终端key" prop="terminalKey">
          <el-input v-model="form.terminalKey" placeholder="请输入终端key" />
        </el-form-item>
        <el-form-item label="mac地址" prop="terminalMac">
          <el-input v-model="form.terminalMac" placeholder="请输入mac地址" />
        </el-form-item>
        <!-- <el-form-item label="定时开机时间" prop="timeOn">
          <el-time-picker clearable v-model="form.timeOn" placeholder="请选择定时开机时间" format="HH:mm" value-format="HH:mm"> </el-time-picker>
        </el-form-item>
        <el-form-item label="定时关机时间" prop="timeOff">
          <el-time-picker clearable v-model="form.timeOff" placeholder="请选择定时关机时间" format="HH:mm" value-format="HH:mm"> </el-time-picker>
        </el-form-item> -->
        <el-form-item label="单次通话时长(分)" prop="terminalKey">
          <el-input-number v-model="form.callTime" placeholder="请输入单次通话时长" :min="0" />
        </el-form-item>
        <el-form-item label="状态" prop="onlineStatus">
          <el-select v-model="form.onlineStatus" placeholder="请选择状态">
            <el-option v-for="dict in online_status" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="启动时间" prop="startTime">
          <el-date-picker clearable v-model="form.startTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择启动时间">
          </el-date-picker>
        </el-form-item> -->
        <!-- <el-form-item label="最后在线时间" prop="offlineTime">
          <el-date-picker clearable v-model="form.offlineTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择最后在线时间">
          </el-date-picker>
        </el-form-item> -->
        <el-form-item label="备注" prop="remark" style="width: 90%">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <p>注：单次通话时长为0时代表不限制</p>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="TelDevice" lang="ts">
import {
  listTelDevice,
  getTelDevice,
  delTelDevice,
  addTelDevice,
  updateTelDevice,
  restartDevice,
  updateUser,
  updateConfig,
  syncXltDeviceList
} from '@/api/device/telDevice';
import { TelDeviceVO, TelDeviceQuery, TelDeviceForm } from '@/api/device/telDevice/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { tel_device_series, use_status, online_status } = toRefs<any>(proxy?.useDict('tel_device_series', 'use_status', 'online_status'));

const telDeviceList = ref<TelDeviceVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const telDeviceFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: TelDeviceForm = {
  id: undefined,
  terminalKey: undefined,
  terminalMac: undefined,
  name: undefined,
  series: undefined,
  ip: undefined,
  deviceCode: undefined,
  heartbeatFrequency: undefined,
  timeOn: undefined,
  timeOff: undefined,
  onlineStatus: undefined,
  startTime: undefined,
  offlineTime: undefined,
  remark: undefined,
  callTime: 0,
  status: 1
};
const data = reactive<PageData<TelDeviceForm, TelDeviceQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    terminalKey: undefined,
    terminalMac: undefined,
    name: undefined,
    series: undefined,
    ip: undefined,
    deviceCode: undefined,
    heartbeatFrequency: undefined,
    timeOn: undefined,
    timeOff: undefined,
    onlineStatus: undefined,
    offlineTime: undefined,
    status: 1,
    params: {}
  },
  rules: {
    id: [{ required: true, message: 'ID不能为空', trigger: 'blur' }],
    terminalKey: [{ required: true, message: '终端key不能为空', trigger: 'blur' }],
    terminalMac: [{ required: true, message: 'mac地址不能为空', trigger: 'blur' }],
    name: [{ required: true, message: '设备名称不能为空', trigger: 'blur' }],
    // series: [{ required: true, message: '设备系列不能为空', trigger: 'change' }],
    // ip: [{ required: true, message: '设备IP不能为空', trigger: 'blur' }],
    // deviceCode: [{ required: true, message: '设备编码不能为空', trigger: 'blur' }],
    heartbeatFrequency: [{ required: true, message: '心跳频率不能为空', trigger: 'blur' }],
    // timeOn: [{ required: true, message: '定时开机时间不能为空', trigger: 'blur' }],
    // timeOff: [{ required: true, message: '定时关机时间不能为空', trigger: 'blur' }],
    onlineStatus: [{ required: true, message: '状态：1在线、2离线不能为空', trigger: 'change' }],
    // startTime: [{ required: true, message: '启动时间不能为空', trigger: 'blur' }],
    // offlineTime: [{ required: true, message: '最后在线时间不能为空', trigger: 'blur' }],
    // status: [{ required: true, message: '状态：不能为空', trigger: 'change' }],
    callTime: [{ required: true, message: '单次通话时长不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询视频话机管理列表 */
const getList = async () => {
  loading.value = true;
  const res = await listTelDevice(queryParams.value);
  telDeviceList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  telDeviceFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: TelDeviceVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加视频话机管理';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: TelDeviceVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getTelDevice(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改视频话机管理';
};

/** 提交按钮 */
const submitForm = () => {
  telDeviceFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      let tipText = '修改成功';
      if (form.value.id) {
        await updateTelDevice(form.value).finally(() => (buttonLoading.value = false));
      } else {
        tipText = '新增成功';
        await addTelDevice(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess(tipText);
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: TelDeviceVO) => {
  const _ids = row?.id || ids.value;
  let tipText = '是否确认删除选中的数据？';
  if (row?.id) {
    tipText = '是否确认删除"' + row.name + '"的数据项？';
  }
  await proxy?.$modal.confirm(tipText).finally(() => (loading.value = false));
  await delTelDevice(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'device/telDevice/export',
    {
      ...queryParams.value
    },
    `telDevice_${new Date().getTime()}.xlsx`
  );
};

const handleUpdateUser = async (row?: TelDeviceVO) => {
  let _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否更新用户信息？').finally(() => (loading.value = false));
  if (!Array.isArray(_ids)) {
    _ids = [_ids];
  }
  await updateUser(_ids);
  proxy?.$modal.msgSuccess('更新成功');
};

const handleUpdateConfig = async (row?: TelDeviceVO) => {
  let _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否更新配置信息？').finally(() => (loading.value = false));
  if (!Array.isArray(_ids)) {
    _ids = [_ids];
  }
  await updateConfig(_ids);
  proxy?.$modal.msgSuccess('更新成功');
};

const handleRestart = async (row?: TelDeviceVO) => {
  let _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认重启选择设备项？').finally(() => (loading.value = false));
  if (!Array.isArray(_ids)) {
    _ids = [_ids];
  }
  await restartDevice(_ids);
  proxy?.$modal.msgSuccess('重启成功');
  await getList();
};

const handleSync = async () => {
  await proxy?.$modal.confirm('是否确认同步话机设备信息？');
  loading.value = true;
  const res = await syncXltDeviceList().finally(() => (loading.value = false));
  proxy?.$modal.msgSuccess(`同步完成，新增设备数量：${res.data.addCount}，更新设备数量：${res.data.updateCount}`);
  await getList();
};

onMounted(() => {
  getList();
});
</script>
